﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Threading.Tasks;
using Xlit.Standard.Data;

namespace Xlit.ORM.EfCore
{
    public interface IEfTransaction : ITransaction { }

    public class EfTransaction : IEfTransaction
    {
        DbContext Context;
        IDbContextTransaction Transaction;

        public EfTransaction(DbContext context)
        {
            Context = context;
        }

        /// <summary>
        ///  创建事务
        /// </summary>
        /// <returns></returns>
        public void BeginTransaction()
        {
            Transaction = Context.Database.BeginTransaction();
        }

        /// <summary>
        ///  提交
        /// </summary>
        /// <returns></returns>
        public void Commit()
        {
            if (Transaction != null)
            {
                Transaction.Commit();
            }
        }

        /// <summary>
        ///  回滚
        /// </summary>
        /// <returns></returns>
        public void RollBack()
        {
            if (Transaction != null)
            {
                Transaction.Rollback();
            }
        }

        /// <summary>
        ///  创建事务
        /// </summary>
        /// <returns></returns>
        public async Task BeginTransactionAsync()
        {
            Transaction = await Context.Database.BeginTransactionAsync();
        }

        /// <summary>
        ///  提交
        /// </summary>
        /// <returns></returns>
        public async Task CommitAsync()
        {
            if (Transaction != null)
            {
                await Transaction.CommitAsync();
            }
        }

        /// <summary>
        ///  回滚
        /// </summary>
        /// <returns></returns>
        public async Task RollBackAsync()
        {
            if (Transaction != null)
            {
                await Transaction.RollbackAsync();
            }
        }
    }
}
